package org.example.common.powerjob;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import tech.powerjob.client.PowerJobClient;
import tech.powerjob.common.response.JobInfoDTO;
import tech.powerjob.common.response.ResultDTO;

import javax.annotation.Resource;
import java.util.Map;

/**
 * PowerJob 延时任务通用工具类（适用于 5.1.2 版本）
 */
@Slf4j
@Component
public class PowerJobDelayTaskUtil {

    @Resource
    private PowerJobClient powerJobClient;



    /**
     * 创建并立即触发延时任务（完整参数）
     * 注意：runJob 方法会立即触发任务，但任务会等待 delayMs 后才执行
     */
    public Long createDelayTask(Long jobId, Long delayMs, Map<String, Object> taskParams) {
        try {
            // 在 5.1.2 版本中，runJob 方法的签名是：runJob(Long jobId, String instanceParams, Long delayTimeMs)
            // runJob 会立即触发任务，但任务会延时 delayMs 后才执行
            String instanceParams = taskParams != null && !taskParams.isEmpty() ?
                    JSONUtil.toJsonStr(taskParams) : null;

            ResultDTO<Long> result = powerJobClient.runJob(jobId, instanceParams, delayMs);

            if (result.isSuccess()) {
                Long instanceId = result.getData();
                log.info("延时任务创建成功, jobId: {}, delayMs: {}, instanceId: {}", jobId, delayMs, instanceId);
                return instanceId;
            } else {
                throw new RuntimeException("创建延时任务失败: " + result.getMessage());
            }
        } catch (Exception e) {
            log.error("创建延时任务失败, jobId: {}, delayMs: {}", jobId, delayMs, e);
            throw new RuntimeException("创建延时任务失败", e);
        }
    }


    /**
     * 获取任务信息
     */
    public JobInfoDTO getJobInfo(Long jobId) {
        try {
            // 在 5.1.2 版本中，方法名是 fetchJob
            ResultDTO<JobInfoDTO> result = powerJobClient.fetchJob(jobId);
            if (result.isSuccess()) {
                return result.getData();
            } else {
                log.warn("获取任务信息失败, jobId: {}, message: {}", jobId, result.getMessage());
                return null;
            }
        } catch (Exception e) {
            log.error("获取任务信息异常, jobId: {}", jobId, e);
            return null;
        }
    }

    /**
     * 停止任务实例
     */
    public boolean stopInstance(Long instanceId) {
        try {
            ResultDTO<Void> result = powerJobClient.stopInstance(instanceId);
            if (result.isSuccess()) {
                log.info("停止任务实例成功, instanceId: {}", instanceId);
                return true;
            } else {
                log.warn("停止任务实例失败, instanceId: {}, message: {}", instanceId, result.getMessage());
                return false;
            }
        } catch (Exception e) {
            log.error("停止任务实例异常, instanceId: {}", instanceId, e);
            return false;
        }
    }
}